package com.yyx.app1.Data;

import android.app.Activity;
import android.content.Context;
import android.os.IInterface;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.yyx.app1.Interface.Trancaction;
import com.yyx.app1.MyApp;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class WebOperation {
    private String[] urls;
    private String rooturl;
    private String filerootpath;
    private String TAG = "正常";

    public WebOperation() {
    }

    public WebOperation(String rooturl, String[] urls, String filerootpath) {
        this.urls = urls;
        this.rooturl = rooturl;
        this.filerootpath = filerootpath;
    }

    public void Download()
    {
        for (int i=0;i<urls.length;++i)
        {
            downloadNet(rooturl+"/" + urls[i], filerootpath +"/"+ urls[i]);
        }
    }


    public boolean downloadNet(String downloadneturl,String path){
        // 下载网络文件
        boolean IsFinish=false;
        try {
            //判断文件大小,是否多线程下载
            // 读取下载文件总大小
            int fileSize = new URL(downloadneturl).openConnection().getContentLength();
            if (fileSize>1024*1024)
            {
                downloadTask thread = new downloadTask(downloadneturl,5,path);
                thread.start();
                while (!IsFinish)
                {
                    Thread.sleep(1000);
                    if(thread.isfinished)
                    {
                        IsFinish = true;
                        break;
                    }
                }
            }
            else
            {
                DownLoadFile downLoadFile = new DownLoadFile(path,downloadneturl,fileSize);
                downLoadFile.start();
                while (!IsFinish)
                {
                    Thread.sleep(1000);
                    if (downLoadFile.isFinish())
                    {
                        IsFinish=true;
                        break;
                    }
                }
            }
        } catch (Exception e) {
           Log.e("异常1510201530", e.toString());
        }
        finally {
            return IsFinish;
        }
    }
    //单线程下载
    class DownLoadFile extends Thread
    {
        private boolean IsFinish=false;
        private String downloadUrl;// 下载链接地址
        private String filePath;// 保存文件路径地址
        private int fileSize;

        public DownLoadFile(String filePath, String downloadUrl,int fileSize) {
            this.filePath = filePath;
            this.downloadUrl = downloadUrl;
            this.fileSize = fileSize;
        }

        public boolean isFinish() {
            return IsFinish;
        }

        @Override
        public void run() {
            try
            {
                int byteread ;
                int bytesum=0;
                URL url = new URL(downloadUrl);
                URLConnection conn = url.openConnection();
                InputStream inStream = conn.getInputStream();
                FileOutputStream fs = new FileOutputStream(filePath);
                byte[] buffer = new byte[1024*1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                if (bytesum == fileSize)
                {
                    IsFinish = true;
                }
            }
            catch (Exception e)
            {
               Log.e("异常1510271455",e.toString());
            }
        }
    }

//    多线程下载
    /**
     * 多线程文件下载
     * @2014-8-7
     */
    class downloadTask extends Thread {
        private String downloadUrl;// 下载链接地址
        private int threadNum;// 开启的线程数
        private String filePath;// 保存文件路径地址
        private int blockSize;// 每一个线程的下载量
        public  boolean isfinished = false;

        public downloadTask(String downloadUrl, int threadNum, String fileptah) {
            this.downloadUrl = downloadUrl;
            this.threadNum = threadNum;
            this.filePath = fileptah;
        }

        @Override
        public void run() {
            FileDownloadThread[] threads = new FileDownloadThread[threadNum];
            try {
                URL url = new URL(downloadUrl);
                Log.d(TAG, "download file http path:" + downloadUrl);
                URLConnection conn = url.openConnection();
                // 读取下载文件总大小
                int fileSize = conn.getContentLength();
                if (fileSize <= 0) {
                    System.out.println("读取文件失败");
                    return;
                }
//                // 设置ProgressBar最大的长度为文件Size
//                mProgressbar.setMax(fileSize);
                // 计算每条线程下载的数据长度
                blockSize = (fileSize % threadNum) == 0 ? fileSize / threadNum
                        : fileSize / threadNum + 1;

                Log.d(TAG, "fileSize:" + fileSize + "  blockSize:");
                File file = new File(filePath);
                for (int i = 0; i < threads.length; i++) {
                    // 启动线程，分别下载每个线程需要下载的部分
                    threads[i] = new FileDownloadThread(url, file, blockSize,
                            (i + 1));
                    threads[i].setName("Thread:" + i);
                    threads[i].start();
                }
                int downloadedAllSize = 0;
                while (!isfinished) {
                    isfinished = true;
                    // 当前所有线程下载总量
                    downloadedAllSize = 0;
                    for (int i = 0; i < threads.length; i++) {
                        downloadedAllSize += threads[i].getDownloadLength();
                        if (!threads[i].isCompleted()) {
                            isfinished = false;
                        }
                    }
//                    // 通知handler去更新视图组件
//                    Message msg = new Message();
//                    msg.getData().putInt("size", downloadedAllSize);
//                    mHandler.sendMessage(msg);
//                    // Log.d(TAG, "current downloadSize:" + downloadedAllSize);
//                    Thread.sleep(1000);// 休息1秒后再读取下载进度
                }
                Log.d(TAG, " all of downloadSize:" + downloadedAllSize);
            } catch (Exception e) {
               Log.e("异常1510270913",e.toString());
            }
        }
    }
    /**
     * 文件下载类
     * @2014-5-6
     */
    public class FileDownloadThread extends Thread {

        /** 当前下载是否完成 */
        private boolean isCompleted = false;
        /** 当前下载文件长度 */
        private int downloadLength = 0;
        /** 文件保存路径 */
        private File file;
        /** 文件下载路径 */
        private URL downloadUrl;
        /** 当前下载线程ID */
        private int threadId;
        /** 线程下载数据长度 */
        private int blockSize;

        /**
//         * @param url:文件下载地址
//         * @param file:文件保存路径
//         * @param blocksize:下载数据长度
//         * @param threadId:线程ID
         */
        public FileDownloadThread(URL downloadUrl, File file, int blocksize,
                                  int threadId) {
            this.downloadUrl = downloadUrl;
            this.file = file;
            this.threadId = threadId;
            this.blockSize = blocksize;
        }

        @Override
        public void run() {
            BufferedInputStream bis = null;
            RandomAccessFile raf = null;
            try {
                URLConnection conn = downloadUrl.openConnection();
                conn.setAllowUserInteraction(true);
                int startPos = blockSize * (threadId - 1);//开始位置
                int endPos = blockSize * threadId - 1;//结束位置
                //设置当前线程下载的起点、终点
                conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
                System.out.println(Thread.currentThread().getName() + "  bytes="
                        + startPos + "-" + endPos);
                byte[] buffer = new byte[1024];
                bis = new BufferedInputStream(conn.getInputStream());

                raf = new RandomAccessFile(file, "rwd");
                raf.seek(startPos);
                int len;
                while ((len = bis.read(buffer, 0, 1024)) != -1) {
                    raf.write(buffer, 0, len);
                    downloadLength += len;
                }
                isCompleted = true;
                Log.d(TAG, "current thread task has finished,all size:"
                        + downloadLength);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (Exception e) {
                       Log.e("异常1510271336", e.toString());
                    }
                }
                if (raf != null) {
                    try {
                        raf.close();
                    } catch (Exception e) {
                       Log.e("异常1510271337", e.toString());
                    }
                }
            }
        }
        /**
         * 线程文件是否下载完毕
         */
        public boolean isCompleted() {
            return isCompleted;
        }
        /**
         * 线程下载文件长度
         */
        public int getDownloadLength() {
            return downloadLength;
        }
    }

    public static void JsonRequest(final Context context,String function,String[] parameterName ,String[] parameterValue, final Trancaction trancaction) {
        StringBuffer httpURL = new StringBuffer(DataInit.httpHead);
        httpURL.append(function).append(".action?").append(parameterName[0]).append("=").append(parameterValue[0]);
        for (int i = 1 ; i<parameterName.length;++i)
        {
            httpURL.append("&").append(parameterName[i]).append("=").append(parameterValue[i]);
        }
        final String str = httpURL.toString();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(httpURL.toString(), null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("正常", str+"->"+response.toString());
                        trancaction.onResponse(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("异常1511041027", str+"->"+error.getMessage(), error);
                Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
                trancaction.onErrorResponse(error);
            }
        }) {
            @Override
            public com.android.volley.Request.Priority getPriority() {
                return trancaction.getPriority();
            }
        };
    }
}